package com.sp.scmdb.webservice.serviceImpl;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sp.scmdb.common.CommonParamter;
import com.sp.scmdb.dao.MapDao;
import com.sp.scmdb.entity.Map;
import com.sp.scmdb.spring.ApplicationContext;
import com.sp.scmdb.webservice.suport.CastorSerializer;
import com.sp.scmdb.webservice.model.MapModel;
import com.sp.scmdb.webservice.model.ReturnResponse;
import com.sp.scmdb.webservice.service.UploadDataService;
import com.sp.scmdb.webservice.service.UploadMapService;

@Service("uploadMapService")
public class UploadMapServiceImpl implements UploadMapService {

	private static Log log = LogFactory.getLog(UploadMapServiceImpl.class);
	private MapDao mapdao;
	
	@Transactional(readOnly = true)
	public List<Map> queryMap() {
		return mapdao.queryAll();
	}
	@Transactional(readOnly = true)
	public List<Map> queryIsUsed() {
		return mapdao.queryHql("from Map where 1=1 and isUsed='1'");
	}
	
	public String uploadMap(){
		String result = "上传成功！";
		try {
			List<Map> mapList = this.queryIsUsed();
			if (CollectionUtils.isNotEmpty(mapList)) {
				Map map = mapList.get(0);
				
				MapModel model = new MapModel();
				model.setMapId(map.getId());
				model.setMapName(map.getMapName());
				model.setMapHeight(map.getMapHeight());
				model.setMapWidth(map.getMapWidth());
				
				model.setUserId(CommonParamter.userID);
				model.setPassword(CommonParamter.password);
				
				CastorSerializer serializerTool = new CastorSerializer();
				ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
				serializerTool.addMappingLocation("com/sp/scmdb/webservice/mapping/mapping.xml");
				serializerTool.marshal(model, byteOutputStream, "UTF-8");
				String str = new String(byteOutputStream.toByteArray());
				
				UploadDataService upload=(UploadDataService )ApplicationContext.getBean("uploadService");
				result = upload.uploadMap(map.getMapAddr(), str);

				// 获取返回值
				ReturnResponse response = (ReturnResponse)serializerTool.unmarshal(new ByteArrayInputStream(result.getBytes()), "GB2312");
				result = response.getDescription();
			}
		} catch (javax.xml.ws.WebServiceException e){
			log.error("uploadMap failed! reason:" + e.getMessage());
			if ("Could not send Message.".equals(e.getMessage())) {
				result = "无法连接到服务器！";
			}
		} catch (Exception e) {
			log.error("uploadMap failed! reason:" + e.getMessage());
			result = e.getMessage();
		}
		return result;
	}
	public void setMapdao(MapDao mapdao) {
		this.mapdao = mapdao;
	}
}
